import { routerEnumeration, routerPath, ROUTER_ENUM } from '@/router/utils/routeMenu'
import { sessionGet, sessionSet } from './sessionStorage'
type RouterSaveType = {
  name: keyof typeof ROUTER_ENUM;
  title: typeof routerEnumeration[keyof typeof ROUTER_ENUM];
  path: typeof routerPath[keyof typeof ROUTER_ENUM];
}
// 存储路由
const routerSave = (name: keyof typeof ROUTER_ENUM) => {
  const router: RouterSaveType = {
    name,
    title: routerEnumeration[name],
    path: routerPath[name]
  }

  const list: Array<RouterSaveType> = sessionGet('_router') || []
  if (list.length) {
    const flag = list.find((item) => item.name === router.name)
    if (!flag) {
      list.push(router)
      sessionSet('_router', list)
    }
  } else {
    list.push(router)
    sessionSet('_router', list)
  }
  return list
}

let path: string = ''

// 关闭路由
const routerClose = (name: keyof typeof ROUTER_ENUM): Array<RouterSaveType> => {
  const router: RouterSaveType = {
    name,
    title: routerEnumeration[name],
    path: routerPath[name]
  }
  const list: Array<RouterSaveType> = sessionGet('_router') || []
  const index = list.findIndex((item) => item.name === router.name)
  const listRouter = list.filter((item) => item.name !== router.name)
  sessionSet('_router', JSON.stringify(listRouter))
  if (index) {
    path = list[index - 1].path
  } else {
    if (listRouter.length) {
      path = list[1].path
    } else {
      path = '/'
    }
  }
  return listRouter
}

// 删除后的下一个路由
const routerNext = (): string => {
  return path
}

// 全部关闭
const AllClose = (): Array<null> => {
  sessionStorage.setItem('_router', JSON.stringify([]))
  path = '/'
  return []
}
export { routerSave, routerClose, AllClose, routerNext }
export type { RouterSaveType }